/*
 * BrowsingHistoryPresenter.java
 * business
 *
 * Created by SunDing on 2016/9/9.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.browsing;

import android.support.v4.util.ArrayMap;

import com.yidiandao.business.constant.Common;
import com.yidiandao.business.data.realm.BrowingHistoryBean;
import com.yidiandao.business.ui.widget.listview.DisplayListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.BrowsingHistoryListItem;
import com.yidiandao.business.ui.widget.view.SuperLoadingLayout;
import com.yidiandao.business.utils.PreferenceUtils;

import java.util.ArrayList;

import io.realm.Realm;
import io.realm.RealmChangeListener;
import io.realm.RealmResults;

/**
 * 我的 浏览历史
 */
public class BrowsingHistoryPresenter implements BrowsingHistoryContract.Presenter {
    int totalSize; //数据数
    int currentPage; //当前页数
    ArrayList<DisplayListItem> mDisplayListItems = new ArrayList<>();
    BrowsingHistoryActivity mActivity;
    boolean tag = true; //首次加载数据
    private BrowsingHistoryContract.View mView;
    private RealmResults<BrowingHistoryBean> mAllData;
    private RealmResults<BrowingHistoryBean> AllData;
    private Realm mMHistoryRealm;
    private RealmResults<BrowingHistoryBean> mGoods_brand;
    private RealmChangeListener callback =
            new RealmChangeListener() {

                @Override
                public void onChange(Object element) {
                    //搜索全部数据的回调
                    if (tag) {
                        AllData = mAllData; //记录所有的数据
                        mView.refreshContent(mView.checkResultObject(mAllData));
                        totalSize = mAllData.size();
                        getBrand();
                        mView.setTvClearVisible(mAllData.size() != 0);
                    } else {
                        //按品牌搜索的回调
                        mAllData = mGoods_brand;
                        totalSize = mGoods_brand.size();
                        getHistoryData(true);
                    }
                }
            };

    public BrowsingHistoryPresenter(
            BrowsingHistoryActivity browsingHistoryActivity,
            BrowsingHistoryContract.View browsingHistoryFragment) {
        mView = browsingHistoryFragment;
        mView.setPresenter(this);
        mActivity = browsingHistoryActivity;
    }

    @Override
    public void start() {
        getData();
    }

    private void getData() {
        tag = true;
        mMHistoryRealm = mView.getRealm();
        mAllData =
                mMHistoryRealm
                        .where(BrowingHistoryBean.class)
                        .equalTo("userId", PreferenceUtils.getUserId(mActivity))
                        .findAllAsync();
        mAllData.addChangeListener(callback);
    }

    private void getBrand() {
        ArrayMap<String, String> map = new ArrayMap<>();
        for (int i = 0; i < mAllData.size(); i++) {
            map.put(mAllData.get(i).getGoods_brand(), "");
        }
        for (String key : map.keySet()) {
            mView.getTabLayout().addTab(mView.getTabLayout().newTab().setText(key));
        }
    }

    @Override
    public void deleteAll() {
        mDisplayListItems.clear();
        mView.refreshUI();
        mView.refreshContent(SuperLoadingLayout.STATE_EMPTY);
        mMHistoryRealm.executeTransaction(
                new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        AllData.deleteAllFromRealm();
                    }
                });
    }

    @Override
    public void changeData(String tagDataName) {
        tag = false;
        mGoods_brand =
                mMHistoryRealm
                        .where(BrowingHistoryBean.class)
                        .contains("userId", PreferenceUtils.getUserId(mActivity))
                        .equalTo("goods_brand", tagDataName)
                        .findAllAsync();
        mGoods_brand.addChangeListener(callback);
    }

    @Override
    public void getHistoryData(boolean isRefresh) {

        if (isRefresh) {
            currentPage = 0;
            mDisplayListItems.clear();
        }
        if (currentPage * Common.PAGER_SIZE > totalSize) {
            //没有更多数据了
            return;
        }
        //倒序取数据
        int currentStart = totalSize - currentPage * Common.PAGER_SIZE;
        int nextPage = totalSize - (currentPage + 1) * Common.PAGER_SIZE;
        int currentEnd = nextPage > 0 ? nextPage : 0;

        ArrayList<DisplayListItem> displayListItems = new ArrayList<>();

        for (int i = currentStart - 1; i > currentEnd - 1; i--) {
            BrowsingHistoryListItem browsingHistoryListItem =
                    new BrowsingHistoryListItem(mAllData.get(i));
            displayListItems.add(browsingHistoryListItem);
        }
        mDisplayListItems.addAll(displayListItems);
        mView.setDisPlayItems(mDisplayListItems);
        currentPage++;
        if (isRefresh) mView.setRefreshComplete();
        mView.loadMoreFinish(
                displayListItems.size() == 0, currentPage * Common.PAGER_SIZE <= totalSize);
    }

    @Override
    public void destroy() {
        mAllData.removeChangeListener(callback);
    }
}
